<?php
require_once "wxpay/WxPay.Api.php";

class weixin_refund_plugin_wxpay
{
	public function dorefund($sdf, &$msg)
    {
        if(!$sdf["total_amount"]) {
            $msg = 'total_amount 不能为0';
            return false;
        }

        if(!defined('WX_MCHID') || !defined('WX_KEY') || !defined('SSLCERT_PATH')) {
            $msg = "微信退款配置不完善，请联系开发人员或自行去/config/config.php配置WX*";
            return false;
        }
		// 组织参数发起原路退回
        //$transaction_id = $data["transaction_id"];
        $out_trade_no = $sdf["payment_id"];
        $total_fee = $sdf["total_amount"]*100;
        $refund_fee = $sdf["money"]*100;
        $input = new WxPayRefund();
        //$input->SetTransaction_id($transaction_id); //微信支付单号
        $input->SetOut_trade_no($out_trade_no); //订单号 二选一
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $input->SetOut_refund_no(WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(WxPayConfig::MCHID);
        $result = WxPayApi::refund($input);

        $objorder_log = app::get('b2c')->model('order_log');
        $sdf_order_log = array(
            'rel_id' => $sdf['order_id'],
            'op_id' => $sdf['op_id'],
            'op_name' => $sdf['op_name'],
            'alttime' => time(),
            'bill_type' => 'order',
            'behavior' => 'refunds',
        );

        if ($result['result_code'] == 'SUCCESS') {
            $sdf_order_log['result'] = 'SUCCESS';
            $sdf_order_log['log_text'] = '微信支付原路退回：'.$sdf["money"];
            $res = true;
        }else{
            $sdf_order_log['result'] = 'FAILURE';
            $sdf_order_log['log_text'] = '微信支付退款失败原因：'.$result['err_code_des'];
            $res = false;
            if( ! $result['err_code_des']) {
                $result['err_code_des'] = $result['return_msg'];
            }
            $msg = '微信支付退款失败: '.$result['err_code_des'];
        }
        $sdf_order_log['log_text'] = serialize($sdf_order_log['log_text']);
        $objorder_log->save($sdf_order_log);
        return $res;
	}
}

